/**
 * @file BSP_USART.c
 * @author Miraggio (w1159904119@gmail)
 * @brief
 * @version 0.1
 * @date 2021-03-30
 *
 * @copyright Copyright (c) 2021
 *
 */
#include "BSP_USART.h"

void USART_Receive_IT_Init(UART_HandleTypeDef *huartx);
void USART_Send_IT_Init(UART_HandleTypeDef *huartx);
void DMA_USART_Receive_Init(UART_HandleTypeDef *huartx, uint8_t *Buffer);
USART_Fun_t USART_Fun = USART_FunGroundInit;
#undef USART_FunGroundInit

/**
 * @Data    2021/3/26
 * @brief   串口接收中断初始化（关闭DMA中断）
 * @param   void
 * @retval  void
 */
void USART_Receive_IT_Init(UART_HandleTypeDef *huartx)
{
    /*清空标志位然后使能USART的中断*/
    __HAL_UART_CLEAR_IDLEFLAG(huartx);
    __HAL_UART_ENABLE(huartx);
    __HAL_UART_ENABLE_IT(huartx, UART_IT_IDLE);
}


/**
 * @brief USART_DMA接收开启和重定向
 * 
 * @param huart 
 * @param pData 
 * @param Size 
 * @return  
 */
static int USART_Receive_DMA_NO_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint32_t Size)
{

    /*检测当前huart状态*/
    if (huart->RxState == HAL_UART_STATE_READY)
    {
        /*输入的地址或者数据有问题的话*/
        if ((pData == NULL) || (Size == 0))
        {
            return HAL_ERROR;
        }

        /*huart里面对应的Rx变量重定向*/
        huart->pRxBuffPtr = pData;
        huart->RxXferSize = Size;
        huart->ErrorCode = HAL_UART_ERROR_NONE;

        /*开启huart1上的RX_DMA*/
        HAL_DMA_Start(huart->hdmarx, (uint32_t)&huart->Instance->DR, (uint32_t)pData, Size);

        /*只开启对应DMA上面的Rx功能（如果是开启Tx的话就是USART_CR3_DMAT）*/
        SET_BIT(huart->Instance->CR3, USART_CR3_DMAR);
    }
    else
    {
        return HAL_BUSY;
    }

    return HAL_OK;
}


/**
 * @Data    2021/3/26
 * @brief   串口接收DMA处理函数
 * @param   UART_HandleTypeDef *huart
 * @retval  void
 */
void DMA_USART_Receive_Init(UART_HandleTypeDef *huartx, uint8_t *Buffer)
{
    /*清空标志位然后使能USART的中断*/
    USART_Receive_IT_Init(huartx);
    // assert(DR16BufferNumber == 22);
    USART_Receive_DMA_NO_IT(huartx, Buffer, sizeof(Buffer) / sizeof(uint8_t));
}

/**
 * @Data    2021/3/28
 * @brief   串口发送中断初始化（关闭DMA中断）
 * @param   void
 * @retval  void
 */
void USART_Send_IT_Init(UART_HandleTypeDef *huartx)
{
    /*清空标志位然后使能USART的中断*/
    __HAL_UART_CLEAR_IDLEFLAG(huartx);
    __HAL_UART_ENABLE(huartx);
    __HAL_UART_ENABLE_IT(huartx, UART_IT_TXE);
}
